
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class SelectableTextPage extends StatefulWidget {
  const SelectableTextPage({Key? key}) : super(key: key);

  @override
  State<SelectableTextPage> createState() => _SelectableTextPageState();
}

class _SelectableTextPageState extends State<SelectableTextPage> {
  final List<GlobalKey> _textKeys = List.generate(3, (_) => GlobalKey());
  final List<FocusNode> _focusNodes = List.generate(3, (_) => FocusNode());
  int? _activeIndex;
  List<String> _textWidgetKeys = List.generate(3, (index) => 'text_$index');

  void _clearOtherTextSelections(int currentIndex) {
    setState(() {
      // 通过重新生成widget key来强制重建其他SelectableText，从而清除选择状态
      for (int i = 0; i < _textKeys.length; i++) {
        if (i != currentIndex) {
          _focusNodes[i].unfocus();
          _textWidgetKeys[i] = 'text_${i}_${DateTime.now().millisecondsSinceEpoch}';
        }
      }
    });
  }

  void _handleTap(int index) {
    setState(() {
      _clearOtherTextSelections(index);
      _activeIndex = index;
    });
  }

  void _handleSelectionChanged(int index, TextSelection selection, SelectionChangedCause? cause) {
    if (selection.isValid && !selection.isCollapsed) {
      _clearOtherTextSelections(index);
      setState(() {
        _activeIndex = index;
      });
    }
  }

  @override
  void dispose() {
    for (final focusNode in _focusNodes) {
      focusNode.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SelectableText'),
      ),
      body: buildInteractiveViewer2Widget( context)
    );
  }
  @override
  Widget buildInteractiveViewer2Widget(BuildContext context) {
    return Column(
      children: [
        for (int i = 0; i < 3; i++)
          GestureDetector(
            onTap: () => _handleTap(i),
            child: SelectableText(
              "文本 用户可拖动鼠标选中任意部分文字 用户可拖动鼠标选中任意部分文字${i + 1}用户可拖动鼠标选中任意部分文字",
              key: ValueKey(_textWidgetKeys[i]),
              focusNode: _focusNodes[i],
              onSelectionChanged: (selection, cause) => _handleSelectionChanged(i, selection, cause),
            ),
          ),
      ],
    );
  }
}